package com.lee.impl;

import com.lee.Interface.IMethod;
import com.lee.constant.CommonConstant;
import com.lee.dto.base.BaseResponse;
import com.lee.dto.base.RequestInfo;
import com.lee.limiter.maplimit.RateLimitPolicy;
import com.lee.limiter.maplimit.RateLimiter;

/**
 * User:liwei
 * Date:2017/8/31
 * Time:14:55
 */
public abstract class AbstractMethod implements IMethod {

//    //每1S中的缓存计数器（另外过期时间设置为两秒，保证一秒内的数据是存在的。）
//    private volatile static LoadingCache<Long, AtomicLong> counter =
//            CacheBuilder.newBuilder()
//                    .expireAfterWrite(2, TimeUnit.SECONDS)
//                    .build(new CacheLoader<Long, AtomicLong>() {
//                        @Override
//                        public AtomicLong load(Long seconds) throws Exception {
//                            return new AtomicLong(0);
//                        }
//                    });
//
//    //每秒中的请求限制数量
//    public static long permit = 50;

//    private volatile static RateLimiter rateLimiter = RateLimiter.create(49.0);//每S 50个

    private RateLimiter rateLimiter = new RateLimiter.Builder().newRateLimiter(new RateLimitPolicy(100,10000,10000));

    /**
     * 先实现限流，再走业务
     *
     * @param requestInfo
     * @return
     */
    public BaseResponse doMethod(RequestInfo requestInfo) {
        BaseResponse response = new BaseResponse();
//        long currentSecond = System.currentTimeMillis() / 1000;
            try {
//            if (counter.get(currentSecond).incrementAndGet() > permit) {
//                response.setSuccess(CommonConstant.ERROR);
//                response.setErrorCode("5000");
//                response.setErrorMsg("请求过于频繁");
//            } else {
//                //受理成功
//                return execute(requestInfo);
//            }


//            if (!rateLimiter.tryAcquire()) {
//                response.setSuccess(CommonConstant.ERROR);
//                response.setErrorCode("5000");
//                response.setErrorMsg("请求过于频繁");
//            } else {
//                //受理成功
//                return execute(requestInfo);
//            }

//         String key
                if (!rateLimiter.access(requestInfo.getAceessKey())) {
                    response.setSuccess(CommonConstant.ERROR);
                    response.setErrorCode("5000");
                    response.setErrorMsg("请求过于频繁");
                } else {
                    //受理成功
                    return execute(requestInfo);
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 每个子类实现不同的业务内容
     *
     * @param requestInfo
     * @return
     */
    public abstract BaseResponse execute(RequestInfo requestInfo);
}
